package com.bw.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.bw.common.constants.TokenConstants;
import com.bw.common.domain.Admin;
import com.bw.common.utils.JwtUtils;
import com.bw.mq.utils.TelSmsUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author：HaoYunde
 * @Package：com.bw.mq.consumer
 * @Project：hyd-boot
 * @name：ConsumerPlay
 * @Date：2024/6/17 14:22
 */
@Component
@Log4j2
public class ConsumerPlay {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private TelSmsUtils telSmsUtils;

    /**
     * 退款成功之后需要异步短信通知用户
     * @param message
     * @param channel
     */
    @RabbitListener(queues = "cg")
    public void  consumerPlay(Message message, Channel channel){
        //获取当前登录人信息
        String header = request.getHeader(TokenConstants.TOKEN);
        String key = JwtUtils.getUserKey(header);
        System.out.println(key);
        String s = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + header);
        Admin admin = JSONObject.parseObject(s, Admin.class);
        String adminPhone = admin.getAdminPhone();
        telSmsUtils.sendSms(adminPhone,new HashMap<String,String>());
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.info("发送失败：{}",e);
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

}
